<?php
namespace classes;
class UploadFile{	
	
	/**
	* 构建文件上传的数组,形式为二维索引+关联
	*
	* @access protected 
	* @param  void
	* @return array,返回数组
	*/
	protected function _bulidUploadInfo(){
		foreach($_FILES as $files){
			if(is_array($files['name'])){		
				$n = 0;
				foreach($files['name']  as $key => $filename){
					if($files['error'][$key] === UPLOAD_ERR_OK){
					    $fileInfo[$n]['name'] = $filename;
					    $fileInfo[$n]['type'] = $files['type'][$key] ;
					    $fileInfo[$n]['size'] = $files['size'][$key];					    
					    $fileInfo[$n]['tmp_name'] = $files['tmp_name'][$key];
					    $n++;
					}					
				}
			} else {
				if($files['error'] === UPLOAD_ERR_OK){
					unset($files['error']);
					$fileInfo[] = $files;
				}
			}
		}	
		return $fileInfo;	
	}	
	protected function getExtension($filename){
		return strtolower(pathinfo($filename,PATHINFO_EXTENSION));
	}
	/**
	 * 产生UUID
	 * @access protected
	 * @param  void
	 * @return string
	 */
	protected function uuid(){
		return md5(uniqid(microtime() . mt_rand()));
	}

	/**
	 * 上传文件
	 * @param array $config,上传时的配置选项,包含
	 * destination,上传的目录位置
	 * allows,允许上传的文件类型,以字符串形式表示,默认为'gif,jpg,jpeg,png'
	 * @return array,返回由所有成功上传文件的名称所组成数组
	 */
	public function upload($config=array()){
		if(!isset($config['allows'])){
			$config['allows'] = 'gif,jpg,jpeg,png';
		}
		$uploadedFiles = array();		
		if(isset($config['destination']) && !file_exists($config['destination'])){
			mkdir($config['destination'],0777,true);
		}
		if(!isset($config['destination'])){
			$config['destination'] = './';
		}
		if(isset($config['destination']) && substr($config['destination'],-1) != '/'){
			$config['destination'] .= '/';
		}				
		$files = $this->_bulidUploadInfo();
		
		foreach ($files as $file) {
			$extension =  $this->getExtension($file['name']);
			$allows = explode(',',$config['allows']);
			$bool = in_array($extension, $allows);
			if($bool){
				$filename = $this->uuid() . '.' .$extension;
				move_uploaded_file($file['tmp_name'], $config['destination'] . $filename);
				$uploadedFiles[] = $filename; 
			}			
		}
		return $uploadedFiles;
	}	
}